package org.douxiaoban.client.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import com.google.gdata.data.*;
import com.google.gdata.data.client.DoubanService;
import com.google.gdata.data.douban.*;
import com.google.gdata.data.extensions.Rating;
import com.google.gdata.data.introspection.Categories;
import com.google.gdata.util.ParseException;
import com.google.gdata.util.ServiceException;

import com.google.gdata.util.XmlBlob;
//import com.sun.deploy.net.HttpResponse;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.HTMLElements;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.ThreadTool;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//import sun.net.www.http.HttpClient;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import net.htmlparser.jericho.Source;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-3-22
 * Time: 下午11:56
 */

public class DoubanApi {

	public static DoubanService doubanService;
	
	private static DoubanApi doubanApi;
	
	//    public static String API_KEY = "0c24ab2802ed7223246e017808c85669";
	//    public static String API_SECRET = "815e4612be0cd90f";
	
	private  String currentUserId = "38533562";
	private  String currentUserName = "6a209";
	
	public static String API_KEY = "0977b2d29f59cb971c671877de0d62c5";
	public static String API_SECRET = "49f97d6618b70eca";
	
	public static String ACCESS_TOKEN ;
	public static String ACCESS_SECRET ;
	public static String UID;
	public static String USER_NAME;
	
	

     //用于解析机的零时变量
    private String m_sLinkTemp;

    //从html里解析出来的类型
    public enum eItemType{
    	//相片
    	PHOTOS_PHOTO,
    	//相册
    	PHOTOS_ALBUM,
    	PEOPLE,
    	SUBJECT_MOVIE,
    	SUBJECT_BOOK,
    	SUBJECT_MUSIC,
    	UN_KNOW
    };

//    public static DoubanApi getInstance(){
//        if(doubanApi == null){
//    		doubanApi = new DoubanApi(Assistant.APP_NAME, API_KEY,API_SECRET);
//    		//just for test
//    	//	ArrayList<String> list = doubanApi.getAccessToken();
//    		doubanApi.setAccessToken();
//    	}
//    	return doubanApi;
//
//    }

    public DoubanApi(String name, String oauthKey, String oauthSecret) {
    	DoubanApi.doubanService = new DoubanService(Assistant.APP_NAME,
                oauthKey,
                oauthSecret); 	
    }
    /**
     * Step1 init doubanservice object
     */
//     public DoubanApi() {
//        this.doubanService =new DoubanService(Assistant.APP_NAME,API_KEY,API_SECRET);
//     }

    /**
     * Step2 If AccessToken is null,
     * return requestTokenURL to user by Oauth Validate
     * @return
     */
     public String getRequestTokenURLString() {
         return this.doubanService.getAuthorizationUrl(null);
    }

    /**
     * Step3 If validate success,return AccessToekn tokenkey
     * @return
     */
    private ArrayList getAccessToken() {
        return this.doubanService.getAccessToken();
    }

    /**
     * Step4 Oauth success!
     */
    public void setAccessToken() {
    	this.doubanService.setAccessToken(ACCESS_TOKEN,ACCESS_SECRET);
    }

    /**
     * 获取miniblog数据的接口
    * @param  
    * @return 
    * @exception
     */
    public ArrayList<MiniBlogItemData> getMiniblog(String userId,
    											   int startIndex, 
    											   int maxResult, 
    											   boolean isContacts){
    	
    	if(isContacts){
    		return getContactsMiniblogs(userId, startIndex, maxResult);
    	}else{
    		return getUserMiniblog(userId, startIndex, maxResult);
    	}
    }
    
    /**
     * 返回用户的广播,只有用户的
     * @param userId       用户名
     * @param startIndex  起始索引,
     * @param maxResult	  返回最大值
     * @return
     */
    private ArrayList<MiniBlogItemData> getUserMiniblog(String userId, int startIndex, int maxResult){
    	ArrayList<MiniBlogItemData> listData = new ArrayList<MiniBlogItemData>();

    	try{
    		MiniblogFeed mf  = doubanService.getUserMiniblogs(userId, startIndex, maxResult);
    		currentUserId = mf.getAuthors().get(0).getUri();
    		currentUserId = currentUserId.replace("http://api.douban.com/people/", "");
    		currentUserName = mf.getAuthors().get(0).getName();
        	for(MiniblogEntry me: mf.getEntries()){
        		listData.add(parseMiniblogEntry(me, false));
        	}
        	return listData;
    	} catch (IOException e) {
			e.printStackTrace();
		}catch (ServiceException e) {
			e.printStackTrace();
		}
    	return null;
    }

    /**
     * 返回用户友邻的广播,包括自己的!!!
     * @param userId	用户名
     * @param startIndex 起始索引
     * @param maxResult  最大值
     * @return
     */
    private ArrayList<MiniBlogItemData> getContactsMiniblogs(String userId, int startIndex, int maxResult ){
    	ArrayList<MiniBlogItemData> listData = new ArrayList<MiniBlogItemData>();
    	try{
    		MiniblogFeed mf  = doubanService.getContactsMiniblogs(userId, startIndex, maxResult);
        	for(MiniblogEntry me: mf.getEntries()){
        		listData.add(parseMiniblogEntry(me, true));
        	}
        	return listData;
    	} catch (IOException e) {
			e.printStackTrace();
		}catch (ServiceException e) {
			e.printStackTrace();
		}
    	return null;
    }
    /**
     * 创建我说
     * @param content 创建的内容
     * @return true 成功, false 失败
     */
    public boolean createSaying(String content){
    	try{
    		doubanService.createSaying(content);
    		return true;
    	}catch(ParseException e){
    		return true;
    	}catch(IOException e){
    		e.printStackTrace();
    	} catch( ServiceException e){
    		e.printStackTrace();
    	}
    	return false;
    }

    /**
     * 删除广播
     * @param id 要被删除的广播id
     * @return	 成功返回ture,失败返回false
     */
    public boolean deleteMiniBlog(String id){
      	try{
    		doubanService.deleteMiniblog(id);
    		return true;
    	}catch(ParseException e){
    		return true;
    	} catch(IOException e){
    		e.printStackTrace();
    	} catch( ServiceException e){
    		e.printStackTrace();
    	}
    	return false;
    }

    /**
     * 回应我说
     * @param content  回应的内容
     * @param id	   被回应我说的id
     * @return		   成功返回true
     */
    public boolean revSaying(String content, String id){
    	try{
    		doubanService.revSaying(content, id);
    		return true;
    	}catch(ParseException e){
    		return true;
    	}catch(IOException e){
    		e.printStackTrace();
    	} catch( ServiceException e){
    		e.printStackTrace();
    	}
    	return false;
    }
    /**
     * 回应推荐
     * @param content 回应的内容
     * @param id	  被回应的推荐id
     * @return 		  成功返回true
     */
    public boolean revRecommend(String content, String id){
    	try{
    		doubanService.revRecommendation(content, id);
    		return true;
    	} catch(IOException e){
    		e.printStackTrace();
    	} catch( ServiceException e){
    		e.printStackTrace();
    	}
    	return false;
    }

    private MiniBlogItemData parseMiniblogEntry(MiniblogEntry me, boolean isContacts){
		MiniBlogItemData data = new MiniBlogItemData();

        Set<Category> categorys = me.getCategories();
        if(!categorys.isEmpty()){
            Category category = (Category)categorys.toArray()[0];
            data.m_itemType = getItemType(category.getTerm());
        }else{
             data.m_itemType = MiniBlogItemData.getItemType("unknow");
        }		//toArray 会转换成一个数组哦!

		//HtmlTextConstruct 用来获取html
		TextContent textContent = (TextContent)me.getContent();
		HtmlTextConstruct htmlConstruct = (HtmlTextConstruct)textContent.getContent();

		data.m_sContent =  htmlConstruct.getPlainText();
		data.m_sHtmlContetn = htmlConstruct.getHtml();
		
		parseHtmlContent(data, data.m_sHtmlContetn);

		//是不是所有关注者的广播（包括自己。
		if(isContacts){
			data.m_sName = me.getAuthors().get(0).getName();
			String uri = me.getAuthors().get(0).getUri().replace("http://api.douban.com/people/", "");
			data.m_sUserId = uri;
			data.m_sAvatarLink = "http://t.douban.com/icon/u" + uri + "-100.jpg";
		}else{
			data.m_sName = currentUserName;
			data.m_sUserId = currentUserId;
			data.m_sAvatarLink = "http://t.douban.com/icon/u" + currentUserId + "-100.jpg";
		}
		Link link = me.getLink("image", null);
		if(null != link){
			data.m_sImageLink = link.getHref();
		}
		data.m_sTime = me.getPublished().toUiString();
		data.m_sTime = data.m_sTime.substring(5);
		String id =  me.getId().replace("http://api.douban.com/miniblog/", "");
		data.mId = Integer.parseInt(id);

		//解析推荐id
		if(MiniBlogItemData.ItemType.RECOMMENDATION == data.m_itemType){
			link = me.getLink("related", null);
			if(null != link){
				data.m_sRecommendId = link.getHref();
				data.m_sRecommendId =
					data.m_sRecommendId.replace("http://api.douban.com/recommendation/","");

			}

		//如果是关注,解析其关注的对象id
		}else if(MiniBlogItemData.ItemType.CONTACT == data.m_itemType){
			link = me.getLink("related", null);
			if(null != link){
				data.m_sOtherUserId = link.getHref();
				data.m_sOtherUserId =
					data.m_sOtherUserId.replace("http://api.douban.com/people/", "");
				data.m_sOtherUserName = data.m_sContent.replace("关注","");
			}
		}


		return data;
    }

    //解析获取"miniblog."后面的数据
    private MiniBlogItemData.ItemType getItemType(String str){
    	int start = str.indexOf("#miniblog.");
    	String type = str.substring(start+10, str.length());
    	
    	if(null == MiniBlogItemData.getItemType(type)){
    		//online,(线上活动
    		return MiniBlogItemData.getItemType("unknow");
    	}else{
    		return MiniBlogItemData.getItemType(type);
    	}
    	
    }

    //获取验证用户信息
    public UserInfoData getAuthorizedUser(){
    	UserEntry userEntry = new UserEntry();
    	try{
    		 userEntry  = doubanService.getAuthorizedUser();
    	}catch(IOException e) {
			e.printStackTrace();
			return null;
		}catch(ServiceException e) {
			e.printStackTrace();
			return null;
		}
		return parseUserEntry(userEntry);
    }

    //获取指定用户id 信息!!!
    public UserInfoData getUserInfo(String userId){
    	UserEntry userEntry = new UserEntry();
    	try{
    		 userEntry  = doubanService.getUser(userId);
    	}catch(IOException e) {
			e.printStackTrace();
			return null;
		}catch(ServiceException e) {
			e.printStackTrace();
			return null;
		}
		return parseUserEntry(userEntry);
    }
    
    /**
     * 获取用户列表接口
    * @param  
    * @return 
    * @exception
     */
    public ArrayList<UserInfoData> getUsers(String userId, int startIndex, int maxResult, boolean isContacts){
    	if(isContacts){
    		return getContacts(userId, startIndex, maxResult);
    	}else{
    		return getFriends(userId, startIndex, maxResult);
    	}
    }
    //获取关注列表
    private ArrayList<UserInfoData> getContacts(String userId, int startIndex, int maxResult){
    	UserFeed uf = new UserFeed();
    	try{
    		 uf  = doubanService.getUserContacts(userId, startIndex, maxResult);
    	}catch(IOException e){
    		e.printStackTrace();
    		return null;
    	}catch(ServiceException e){
    		e.printStackTrace();
    		//return null;
    	}
    	ArrayList<UserInfoData> list = new ArrayList<UserInfoData>();
    	for(UserEntry ue: uf.getEntries()){
    		 UserInfoData userInfo = parseUserEntry(ue);
    		 list.add(userInfo);
    	}
    	return  list;
    }

    //获取好友列表
    private ArrayList<UserInfoData> getFriends(String userId, int startIndex, int maxResult){
    	UserFeed uf = new UserFeed();
    	try{
    		 uf  = doubanService.getUserFriends(userId, startIndex, maxResult);
    	}catch(IOException e){
    		e.printStackTrace();
    		return null;
    	}catch(ServiceException e){
    		e.printStackTrace();
    		return null;
    	}
    	ArrayList<UserInfoData> list = new ArrayList<UserInfoData>();
    	for(UserEntry ue: uf.getEntries()){
    		 UserInfoData userInfo = parseUserEntry(ue);
    		 list.add(userInfo);
    	}
    	return  list;
    }

	private UserInfoData parseUserEntry(UserEntry userEntry){
        ThreadTool threadTool = new ThreadTool(null);
		UserInfoData userInfo = new UserInfoData();
		//别用uid
		userInfo.mId = userEntry.getLink("self", null).getHref();
		userInfo.mId = userInfo.mId.replace("http://api.douban.com/people/", "");
		
		userInfo.mName = userEntry.getTitle().getPlainText();
		userInfo.mImageUrl = userEntry.getLink("icon", null).getHref();

        try {
            userInfo.mAvatar = loadImgByURL(new URL(userInfo.mImageUrl));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        userInfo.mLocation = "常居: " + userEntry.getLocation();
		userInfo.mSignature = userEntry.getSignature();
		//Log.v("signature is", userInfo.mSignature);
		if(userEntry.getLink("homepage", null) != null){
			//获取rel = homepage 的link
			userInfo.mSummary = "博客: " + userEntry.getLink("homepage", null).getHref();
			userInfo.mSummary = userInfo.mSummary.concat(" \n\n");
		}else{
			userInfo.mSummary = " ";
		}
		String summary = ((TextContent) userEntry.getContent()).getContent().getPlainText();
		userInfo.mSummary = userInfo.mSummary.concat(summary);
		return userInfo;
	}

     private Bitmap loadImgByURL(URL url) {
        Bitmap image = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

	/**
	 * 解析包含html的content
	 *
	 * @param itemData 解析后数据存放处
	 * @param html	   将要被解析的html
	 */
	private void parseHtmlContent(MiniBlogItemData itemData, String html){
		ArrayList<String> list = new ArrayList<String>();
		int start = 0;
		int end;
		int index;
		index = html.indexOf("href=\"", start);

		//匹配出所有link
		while(-1 != index){
			end = html.indexOf("</a>", index);
			if(-1 == end){
				//跳出此次匹配..
				continue;
			}

			if(index + 6 > html.length()){
				return;
			}
			Log.v("link is :", html);
			String slink = html.substring(index+6, end);
			list.add(slink);
			index = html.indexOf("href=\"",end);
		}
		if(0 == list.size()){
			return;
		}

		//将匹配出的link里的数据放到对应的itemData中
		for(String link : list){
			//m_sLinkTemp = link;
			eItemType type = parseLinkType(link);
//			if(eItemType.UN_KNOW == type){
//				return;
//			}
//			 dataLink = new LinkData();
			 LinkData dataLink = parseLinkData(link, type);
			//有的是以‘/’结尾，有的不是！
			if(eItemType.UN_KNOW != type && dataLink.id.endsWith("/")){
				dataLink.id = dataLink.id.substring(0, dataLink.id.length()-1);
			}
			switch(type){
				case PEOPLE:
					itemData.m_sOtherUserId = dataLink.id;
					itemData.m_sOtherUserName = dataLink.content;
					break;
				case PHOTOS_PHOTO:
					itemData.m_sImageLink =
						//"http://img3.douban.com/view/photo/photo/public/p" + link + ".jpg"; 大图
						"http://img3.douban.com/view/photo/icon/public/p" + dataLink.id + ".jpg";
					break;

				case PHOTOS_ALBUM:
					itemData.m_sAlbumId = dataLink.id;
					break;

				case SUBJECT_MOVIE:
					itemData.mFavorityType = MiniBlogItemData.FavorityType.MOVIE;
					itemData.m_sSubjectId = dataLink.id;
					itemData.m_sSubjectName = dataLink.content;
					break;

				case SUBJECT_MUSIC:
					itemData.mFavorityType = MiniBlogItemData.FavorityType.MUSIC;
					itemData.m_sSubjectId = dataLink.id;
					itemData.m_sSubjectName = dataLink.content;
					break;

				case SUBJECT_BOOK:
					itemData.mFavorityType = MiniBlogItemData.FavorityType.BOOK;
					itemData.m_sSubjectId = dataLink.id;
					itemData.m_sSubjectName = dataLink.content;
					break;
				case UN_KNOW:
					itemData.mUnKnowContent = dataLink.content;
					itemData.mUnKnowContentLink = dataLink.id;
					break;
					default:
						break;
			}
		}
	}

	private eItemType parseLinkType(String str){
		if(str.contains("people")){
			return eItemType.PEOPLE;

		}else if(str.contains("photos/photo")){
			return eItemType.PHOTOS_PHOTO;

//		}else if(str.contains("photos/album")){
//			return eItemType.PHOTOS_ALBUM;

		}else if(str.contains("movie") && str.contains("subject")){
			return eItemType.SUBJECT_MOVIE;

		}else if(str.contains("book") && str.contains("subject")){
			return eItemType.SUBJECT_BOOK;

		}else if(str.contains("music") && str.contains("subject")){
			return eItemType.SUBJECT_MUSIC;
		}
		return eItemType.UN_KNOW;
	}

	private LinkData parseLinkData(String str, eItemType type){
		LinkData data = new LinkData();
		String id;
		int start;
		int end = str.indexOf("\">");
		start = end + 2;
		Log.v("end is:", String.valueOf(end));
		Log.v("String str", str);
		id = str.substring(0, end);
		
		switch(type){
			case PEOPLE:
				id = id.replace("http://www.douban.com/people/", "");
				break;
			case PHOTOS_PHOTO:
				id = id.replace("http://www.douban.com/photos/photo/", "");
				break;
			case PHOTOS_ALBUM:
				id = id.replace("http://www.douban.com/photos/album/", "");
				break;
			case SUBJECT_MOVIE:
			case SUBJECT_BOOK:
			case SUBJECT_MUSIC:
				int index = str.indexOf("subject/");
				id = str.substring(index + 8, end);
				//str = str.replace("http://movie.douban.com/subject/", "");
				break;
			case UN_KNOW:
				break;
			default:
				break;
	   }
	 data.id = id;
	 data.content = str.substring(start);;
	 return data;
	}

	/**
	 * 解析html content中的userName
	 * @param data 解析后的数据存放处
	 */
	private void paseLinkUserName(MiniBlogItemData data){
		int start = data.m_sHtmlContetn.indexOf(">");
		int end = data.m_sHtmlContetn.indexOf("</a>");

	//	data.m_sRecommendUserName = data.m_sHtmlContetn.substring(start+1,end);
	}

	//一个数据结构，表示一个链接
	private class LinkData{
		String id;
		String content;
	}
	
	/**
	 * 获取豆邮接口
	* @param  
	* @return 
	* @exception
	 */
	public ArrayList<MailData> getMail(int start, int max, boolean isInbox){
		if(isInbox){
			return getInboxMail(start, max);
		}else{
			return getOutboxMail(start, max);
		}
	}

	private ArrayList<MailData> getInboxMail(int index, int max) {
		ArrayList<MailData> list = new ArrayList<MailData>();
		try{
			MailFeed mf = doubanService.getInboxMail(index, max);
			for(MailEntry me : mf.getEntries()){
				list.add(parseMailEntry(me, true));
			}
			return list;
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServiceException e){
			e.printStackTrace();
		}
		return null;
	}
	
	private ArrayList<MailData> getOutboxMail(int index, int max){
		ArrayList<MailData> list = new ArrayList<MailData>();
		try{
			MailFeed mf = doubanService.getOutboxMail(index, max);
			for(MailEntry me : mf.getEntries()){
				list.add(parseMailEntry(me, false));
			}
			return list;
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServiceException e){
			e.printStackTrace();
		}
		return null;
	}

	public MailData getOneMail(String mailId){
		MailData mail;
		try{
			MailEntry me = doubanService.getOneMail(mailId);
			mail = parseMailEntry(me, false);
			return mail;
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServiceException e){
			e.printStackTrace();
		}
		return null;
	}



	//
	public int sendMail(String userId, String title, String content, Bundle bundle){
		try{
			doubanService.sendMail(userId, title, content);
			return Assistant.MSG_SUCCESS;
		}catch(IOException e){
			e.printStackTrace();		
		}catch(ParseException e){
			//xml 的错误，放过当成功
			return Assistant.MSG_SUCCESS;
		}catch(ServiceException e){
			//e.printStackTrace();
			//当是403时,需要解析验证码 
			if(e.getHttpErrorCodeOverride() == 403){
				String captcha = e.getResponseBody();
				parseCaptcha(captcha, bundle);
				return Assistant.MSG_NEED_CAPTCHA;	
			}
		}
		return Assistant.MSG_UN_SUCCESS;
	}

	//包含验证参数....
	public int  sendMail(String userId,
						 String title,
						 String content,
						 String captcha_token,
						 String captcha_string,
						 Bundle bundle){

		try{
			doubanService.sendMail(userId, title, content, captcha_token, captcha_string);
			return Assistant.MSG_SUCCESS;
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServiceException e){
			e.printStackTrace();
			//当验证码输错时，
			if(e.getHttpErrorCodeOverride() == 403){
				String captcha = e.getResponseBody();
				parseCaptcha(captcha, bundle);
				return Assistant.MSG_NEED_CAPTCHA;
			}else if (e.getHttpErrorCodeOverride() == 400){
				//xml解析错误!
				return Assistant.MSG_SUCCESS;
			}
		}
		return Assistant.MSG_UN_SUCCESS;
	}
	
	//删除豆油!
   public boolean deleteMail(String id){
      	try{
    		doubanService.deleteMail(id);
    		return true;
    	} catch(IOException e){
    		e.printStackTrace();
    	} catch( ServiceException e){
    		e.printStackTrace();
    	}
    	return false;
    }

	private MailData parseMailEntry(MailEntry me, boolean isInbox){
		MailData mail = new MailData();
		mail.mIsInbox = isInbox;
		String id = me.getId().replace("http://api.douban.com/doumail/", "");
		mail.mId = Integer.parseInt(id);
		mail.mTitle = me.getTitle().getPlainText();
	    for (Attribute attr : me.getAttributes()) {
		//System.out.println(attr.getName() + " : " + attr.getContent());
	    	String content = attr.getContent();
	    	if(content.equals("false")){
	    		mail.mUnread = false;
	    	}else if(content.equals("true")){
	    		mail.mUnread = true;
	    	}
		}
	    mail.mPublicTime = me.getPublished().toUiString();
		TextContent textContent = (TextContent)me.getContent();

		if(null != textContent){
			mail.mContent = textContent.getContent().getPlainText();
		}else{
			//是获取列表， 将时间改成不显示年份
			mail.mPublicTime = mail.mPublicTime.substring(5);

		}
	    parseSendInfo(mail, me);
	    parseRecInfo(mail,me.getXmlBlob().getBlob());
	    return mail;
	}

	private void parseSendInfo(MailData md, MailEntry me){
		Person author = me.getAuthors().get(0);
		md.mSenderName = author.getName();
		md.mSenderId = author.getUri();
		md.mSenderId = md.mSenderId.replace("http://api.douban.com/people/", "");
		md.mSenderAvatarLink = "http://img3.douban.com/icon/u"+md.mSenderId+"-9.jpg";
	}



	private void parseRecInfo(MailData md, String xml){

		 DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
         try {
				DocumentBuilder dombuilder = domfac.newDocumentBuilder();
					InputStream is =  new ByteArrayInputStream(xml.getBytes());
					Document doc;
					doc = dombuilder.parse(is);
				  org.w3c.dom.Element root = doc.getDocumentElement();
				  NodeList children = root.getChildNodes();
				  for(int i = 0; i < children.getLength(); i++){
					  Node node = children.item(i);
					  if(node.getNodeName().equals("link")){
						  System.out.println("get_link");
						  NamedNodeMap attri  = node.getAttributes();
						  String rel = attri.getNamedItem("rel").getNodeValue();
						  if(rel.equals("icon")){
							 //System.out.println(attri.getNamedItem("href").getNodeValue());
							  md.mRecAvatarLink = attri.getNamedItem("href").getNodeValue();
						  }
					  }else if(node.getNodeName().equals("name")){
						  //System.out.println(node.getFirstChild().getNodeValue());
						  md.mRecName = node.getFirstChild().getNodeValue();
					  }else if(node.getNodeName().equals("uri")){
						  System.out.println(node.getFirstChild().getNodeValue());
						  md.mRecId = node.getFirstChild().getNodeValue().replace("http://api.douban.com/people/", "");
					  }
				  }
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	//when send douMail need captcha
	//return Bundle   contain token and url;
	private Bundle parseCaptcha(String captcha, Bundle bundle){
		String[] strList = captcha.split(";");
		if(0 != strList.length){
			String token = strList[0].replace("captcha_token=", "");
			token = token.replace("&amp", "");
			bundle.putString(Assistant.KEY_CAPTCHA_TOKEN, token);
			String url = "http://www.douban.com/misc/captcha?id=" + token;
			bundle.putString(Assistant.KEY_CAPTCHA_URL, url);
		}
		return bundle;
	}


    //-------------------------------------- by kun---------------------------
	/**
	 * 获得用户的收藏信息
	 *
	 * @param userId
	 *            用户id
	 * @param cat
	 * 				类别
	 * @param tag
	 *            标记的tag
	 * @param status
	 * 				收藏的状态
	 * @param startIndex
	 *            开始索引
	 * @param maxResult
	 *            最大返回结果数目
     * @return collectionRecord 集合
	 */
    public ArrayList<CollectionRecord> getUserCollectonRecords(String userId,
          String cat,String tag, String status, int startIndex, int maxResult){

        try {
          CollectionFeed cf =
                  doubanService.getUserCollections(userId, cat, tag,
                          status, startIndex, maxResult);
           ArrayList<CollectionRecord> records = new ArrayList<CollectionRecord>();


          for(CollectionEntry ce:cf.getEntries()){

             records.add(convertEntriesToRecord(ce,cf.getTotalResults()));
          }


            return records;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取验证码字符串
     * @return
     */
    public String getCaptchaId(){
        HttpGet request = new HttpGet("http://www.douban.com/accounts/login");
        org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();

        try {
            org.apache.http.HttpResponse httpResponse = httpClient.execute(request);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                Source source = new Source(httpResponse.getEntity().getContent());
                List<Element> inputElements = source.getAllElements(HTMLElementName.INPUT);
                for (Element element : inputElements) {
					String name = element.getAttributeValue("name");
					if ("captcha-id".equals(name)) {
						return element.getAttributeValue("value");
					}
				}
            }

        } catch (IOException e) {
           return null;
        }

        return null;
    }

    /**
     * 获取验证码 图
     * @param captchaId
     * @return
     */
    public  Bitmap getCaptchaImg(String captchaId) {

		try {
			URL imageUri = new URL(Assistant.CAPTCHA_URL+captchaId + "&amp;size=m");
			HttpURLConnection httpConn = (HttpURLConnection) imageUri
					.openConnection();
			httpConn.setDoInput(true);
			httpConn.connect();
			InputStream is = httpConn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			Bitmap bitmap = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
 		}
        return null;
	}


	// 登录豆瓣，并获取accessToken
	public  boolean doubanLogin(String email, String password,
			String captchaId, String captchaValue) throws Exception {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(Assistant.LOGIN_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("form_email", email));
		nameValuePairs.add(new BasicNameValuePair("form_password", password));
		nameValuePairs.add(new BasicNameValuePair("source", "simple"));
		nameValuePairs.add(new BasicNameValuePair("captcha-id", captchaId));
		nameValuePairs.add(new BasicNameValuePair("captcha-solution",
				captchaValue));

		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		httpClient.execute(httpPost);
		List<Cookie> cookies = httpClient.getCookieStore().getCookies();
		// 登录成功,开始授权
		if (isLoginStatus(cookies)) {
			return getAccessToken(httpClient);
		}
		return false;
	}

	// 判断是否登录成功
	public static boolean isLoginStatus(List<Cookie> cookies) {
		boolean status = false;
		if (!cookies.isEmpty()) {
			for (int i = 0; i < cookies.size(); i++) {
				Cookie cookie = cookies.get(i);
				// 登录成功
				if ("ue".equals(cookie.getName())) {
					status = true;
					break;
				}
			}
		}
		return status;
	}

	// 取得AccessToken
	private  boolean getAccessToken(DefaultHttpClient httpClient)
			throws Exception {
		String authUrl =  doubanService.getAuthorizationUrl(null);
		String ck = "UMat";
		String oauth_token = doubanService.getRequestToken();
		String ssid = "2e8fa7a8";
		String oauth_callback = "";
		String confirm = "同意";
		HttpPost httpPost = new HttpPost(authUrl);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("ck", ck));
		nameValuePairs.add(new BasicNameValuePair("oauth_token", oauth_token));
		nameValuePairs.add(new BasicNameValuePair("ssid", ssid));
		nameValuePairs.add(new BasicNameValuePair("oauth_callback",
				oauth_callback));
		nameValuePairs.add(new BasicNameValuePair("confirm", confirm));
		httpPost
				.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
		httpClient.execute(httpPost);

		ArrayList<String> tokens = doubanService.getAccessToken();
		if (tokens != null) {
			ACCESS_TOKEN = tokens.get(0);
			ACCESS_SECRET = tokens.get(1);
			Log.d("accessToken", ACCESS_TOKEN);
			Log.d("tokenSecret", ACCESS_SECRET);

			// 获取用户ID

			 UserEntry userEntry =  doubanService.getAuthorizedUser();


            if(userEntry!=null && userEntry.getUid()!=null && userEntry.getTitle()!=null){
               // UID = userEntry.getUid();
                UID = userEntry.getLink("icon", null).getHref();
                String[] uid_arr = UID.split("/");
                String temp = uid_arr[uid_arr.length-1];
                temp = temp.substring(1,temp.length());
                UID =  temp.split("-")[0];

                USER_NAME = userEntry.getTitle().getPlainText();
                App.userId = UID;
                App.username = USER_NAME;
			    return true;
            }
		}
		return false;
	}


    /**
     * 发表电影，图书，音乐的推荐
     *
     * @param commend
     *             推荐标注
     * @param id
     * @return
     */
    public Boolean publishSubjectCommend(String commend,String id) {

        try {
            doubanService.publicSubjectRecommend(commend,id);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (ServiceException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 转化 CollectionEnry 为直接可读的CollectionRecord 集合
     * @param ce
     * @return
     */
    public CollectionRecord convertEntriesToRecord(CollectionEntry ce,int total){
        CollectionRecord record = new CollectionRecord();

         record.total_result = total;
        Subject subject = ce.getSubjectEntry();
        record.title = subject.getTitle().getPlainText();

        DateTime dateTime =  ce.getUpdated();

        record.update_date = dateTime.toUiString();

        if(ce.getId() != null)
                record.id = ce.getId();
        if(subject.getId() != null)
                record.id = subject.getId();

        StringTokenizer tokenizer = new StringTokenizer(record.id,"/");
        for(int i=0;tokenizer.hasMoreTokens();i++){
          record.id = tokenizer.nextToken();
        }


        /**
         * 获取条目简要信息，用作导读，内容已经经过缩减，考虑是否再缩减一部分
         */
       if(ce.getSummary() !=null && ce.getSummary().getPlainText() !=null)
           record.summary = ce.getSummary().getPlainText();
       if(subject.getAuthors().size()>0){
           record.author_name = subject.getAuthors().get(0).getName();
           record.author_uri = subject.getAuthors().get(0).getUri();
       }

        if(ce.getRating() != null)
        record.rating = ce.getRating().getValue();
        /**
         * 获取条目里所有的标签，在显示的时候可以考虑只显示3-5个标签
         */
        for (Tag tag:ce.getTags()){
            record.tags.add(tag.getName());
        }//TODO :标签大小，可以变化显示

        /**
         * 获取条目所有的attribute值，在条目详细页将不再调用接口加载
         */
        for (Attribute ai:subject.getAttributes()){

             record.attribute_content.add(ai.getContent());
             record.attribute_name.add(ai.getName());
        }

        /**
         * 获取条目图片url地址,重新开线程加载
         */
        if(subject.getLinks().size() >= 3){
            record.icon_url = subject.getLinks().get(2).getHref();
            record.icon_url =   record.icon_url.replaceAll("spic","mpic");
        }

        record.status = ce.getStatus().getContent();
         return record;
        //TODO parse more data
    }


    public ArrayList<SubjectRecord> searchSubject(String type,int startIndex,
                                                  String keyword,int maxResult)
            throws IOException, ServiceException {

        SubjectFeed subjectFeed = null;
        ArrayList<SubjectRecord>  subjectRecordArrayList =
                new ArrayList<SubjectRecord>();

        if(type.equals(Assistant.STATUS_BOOK)){
            subjectFeed = doubanService.findBook(keyword,"",startIndex,maxResult);
        }else if(type.equals(Assistant.STATUS_MUSIC)){
            subjectFeed = doubanService.findMusic(keyword,"",startIndex,maxResult);
        }else{
            subjectFeed = doubanService.findMovie(keyword,"",startIndex,maxResult);
        }

        if(subjectFeed == null)return null;

        for(SubjectEntry subjectEntry:subjectFeed.getEntries()){
            System.out.println(subjectEntry.toString());
            subjectRecordArrayList.add(convertToSubjectRecord(subjectEntry,
                                                subjectFeed.getTotalResults()));
        }


        return subjectRecordArrayList;
    }


    /**
     * 获取电影，图书，音乐 详细页面的数据
     * @param category
     * @param id
     * @return
     * @throws IOException
     * @throws ServiceException
     */
    public SubjectRecord getSubjectRecord(String category,String id,String isbn)
                    throws IOException, ServiceException {

        SubjectEntry subjectEntry;
             if(category.equals(Assistant.STATUS_BOOK)){
                //if(isbn!=null&& isbn.equals(""))
                subjectEntry = doubanService.getBook(id,isbn);
            }else if(category.equals(Assistant.STATUS_MOVICE)){
                subjectEntry = doubanService.getMovie(id);
            }else{
                subjectEntry = doubanService.getMusic(id);
            }


        return convertToSubjectRecord(subjectEntry,1);
    }

    /**
     * TODO:///
     * @param subjectEntry
     * @return
     */
    public SubjectRecord convertToSubjectRecord(SubjectEntry subjectEntry,int total){
        if(subjectEntry == null)return null;

        SubjectRecord subjectRecord = new SubjectRecord();
        subjectRecord.totalResult = total;

         subjectRecord.subjectEntry = subjectEntry;
        StringTokenizer tokenizer = new StringTokenizer(subjectEntry.getId());

        subjectRecord.title =  subjectEntry.getTitle().getPlainText();
        for(int i=0;tokenizer.hasMoreTokens();i++){
          subjectRecord.id = tokenizer.nextToken();
        }

        if(subjectEntry.getSummary()!=null &&
                subjectEntry.getSummary().getPlainText() != null)
          subjectRecord.summary = subjectEntry.getSummary().getPlainText();

        if(subjectEntry.getAuthors().size()>0){
           subjectRecord.author_name = subjectEntry.getAuthors().get(0).getName();
           subjectRecord.author_uri = subjectEntry.getAuthors().get(0).getUri();
       }

        subjectRecord.rating_numRatess = subjectEntry.getRating().getNumRaters();
        subjectRecord.rating_average = subjectEntry.getRating().getAverage();
        subjectRecord.rating_max = subjectEntry.getRating().getMax();
        subjectRecord.rating_min = subjectEntry.getRating().getMin();

        if(subjectEntry.getRating()!=null && subjectEntry.getRating().getValue() != null)
        subjectRecord.rating_value = subjectEntry.getRating().getValue();

        subjectRecord.tags =  subjectEntry.getTags();
        subjectRecord.attributes = subjectEntry.getAttributes();

        /**
         * 获取条目图片url地址,重新开线程加载
         */
        if(subjectEntry.getLinks()!=null && subjectEntry.getLinks().size() >= 3)
            subjectRecord.icon_url = subjectEntry.getLinks().get(2).getHref();

        if(subjectEntry.getLinks()!=null && subjectEntry.getLinks().size()>=4)
            subjectRecord.collection_url = subjectEntry.getLinks().get(3).getHref();

        if(subjectEntry.getLinks()!=null && subjectEntry.getLinks().get(1)!=null)
            subjectRecord.subject_url = subjectEntry.getLinks().get(1).getHref();

        if(subjectRecord==null)return null;
        return subjectRecord;
    }

    /**
     * TOOD:///
     * @param id
     * @param type
     * @param start
     * @param maxRsult
     * @return
     */
    public ArrayList<ReviewRecord> getSubjectReviews(String id,String type,
                                                     int start,int maxRsult){
           String[] urls = id.split("/");
           id = urls[urls.length-1];
            ArrayList<ReviewRecord> reviewRecords = new ArrayList<ReviewRecord>();
            ReviewFeed reviewFeed = new ReviewFeed();
            try {
                if(type.endsWith(Assistant.STATUS_BOOK))
                    reviewFeed = this.doubanService.
                            getBookReviews(id,start,maxRsult,"score");

                if(type.endsWith(Assistant.STATUS_MOVICE))
                    reviewFeed = this.doubanService.
                            getMovieReviews(id,start,maxRsult,"score");
                if(type.endsWith(Assistant.STATUS_MUSIC))
                    reviewFeed = this.doubanService.
                            getMusicReviews(id,start,maxRsult,"score");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceException e) {
                e.printStackTrace();
            }

        if(reviewFeed!=null){
            for (ReviewEntry enrty:reviewFeed.getEntries()){
                reviewRecords.add(convertToRevierRecord(enrty,reviewFeed.getTotalResults()));
            }
        }

        return reviewRecords;
    }

    /**
     * 将ReviewEnty 解析为ReviewRecord
     * @param reviewEntry
     * @return
     */
    private ReviewRecord convertToRevierRecord(ReviewEntry reviewEntry,int totalResults){
        ReviewRecord reviewRecord = new ReviewRecord();

        reviewRecord.totalResult = totalResults;
        if(reviewEntry.getRating()!=null)
            reviewRecord.rating =  reviewEntry.getRating().getValue();

        reviewRecord.title = reviewEntry.getTitle().getPlainText();
        reviewRecord.author = reviewEntry.getAuthors().get(0).getName();

        reviewRecord.summary = reviewEntry.getSummary().getPlainText();
        reviewRecord.updateDate = reviewEntry.getUpdated().toUiString();
        reviewRecord.reviewId = reviewEntry.getId();
        reviewRecord.avatar_url = reviewEntry.getAuthors().get(0).getUri();
        String[] avs = reviewRecord.avatar_url.split("/");
        reviewRecord.avatar_url = "http://img5.douban.com/icon/u"
                +avs[avs.length-1]+"-2.jpg";
        XmlBlob xml =  reviewEntry.getXmlBlob();

        if(xml.getBlob()!=null){
            String[] blob = xml.getBlob().split("'");
            reviewRecord.feedback = Integer.valueOf(blob[1]);
            reviewRecord.dig = Integer.valueOf(blob[3]);
        }


    //        reviewRecord.dig = reviewEntry.get

        return reviewRecord;
        //TODO: 解析author 中的link头像
    }

    /**
     *  发表评论
     * @param subjectEntry
     * @param title
     * @param content
     * @param ratingValue
     * @return
     */
    public Boolean publishReview(SubjectEntry subjectEntry, String title,
                                 String content,int ratingValue){

        Rating rating = new Rating();
        rating.setValue(ratingValue);
        ReviewEntry reviewEntry;
        //TODO :hidden now
        try {
           reviewEntry =
                   doubanService.createReview(subjectEntry,new PlainTextConstruct(title),
                    new PlainTextConstruct(content),rating);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (ServiceException e) {
            e.printStackTrace();
            return false;
        }

        if(reviewEntry!=null)
           return true;
        else
          return false;
    }

    /**
     * 获取详细评论数据
     * @param reviewID
     * @return
     */
    public ReviewEntry getReviewFull(String reviewID){
        ReviewEntry entry= new ReviewEntry();
        try {
           entry = doubanService.getReview(reviewID);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }

        return entry;

    }
//-------------------------------------------------------------------
// 2011-8-26  @6a209， 豆瓣 日记 api
//
    public NoteData getNoteData(String noteId){
    	try{
        	 return parseNoteEntry(doubanService.getNote(noteId));
    	}catch (IOException e){
    		e.printStackTrace();
    	}catch (ServiceException e){
    		e.printStackTrace();
    	}
    	return null;
    }
    
    public ArrayList<NoteData> getNoteList(String userId,
    									   int start, int max){
//    	NoteFeed nf;
    	ArrayList<NoteData> list = new ArrayList<NoteData>();
    	try{
    		NoteFeed nf = doubanService.getUserNotes(userId, start, max);
    		 for(NoteEntry ne : nf.getEntries()){
    	    	list.add(parseNoteEntry(ne));
    	     }
    		 return list;
    	}catch (IOException e){
    		e.printStackTrace();
    	}catch (ServiceException e){
    		e.printStackTrace();
    	}
    	return null;
    }

    public boolean sendNote(NoteData nd){
    	return false;
    }
    
    public boolean updateNote(NoteEntry entry){
    	return false;
    }
    
    public boolean removeNote(int noteId){
    	return false;
    }
    
    private NoteData parseNoteEntry(NoteEntry ne){
    	NoteData note = new NoteData();
    	note.mAuthor = parseAuthor(ne.getAuthors().get(0));
    	note.mPublicTime = ne.getPublished().toUiString();
    	TextContent tc = (TextContent) ne.getContent();
    	HtmlTextConstruct htc = (HtmlTextConstruct)tc.getContent();
    	//显示html
    	note.mContent = htc.getHtml();
    	note.mTitle = ne.getTitle().getPlainText();
    	return note;

    }
    
    private UserInfoData parseAuthor(Person person){
    	UserInfoData ui = new UserInfoData();
    	ui.mId = person.getUri();
		ui.mId = 
			ui.mId.replace(Assistant.DOU_BAN_PEOLE, "");
		
		ui.mName = person.getName();
		ui.mImageUrl = Assistant.DOU_BAN_ICON + ui.mId + "-9.jpg";
		return ui;
    }
  //-------------------------------------------------------------------

}
